package jmine.tec.hydra.script.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import jmine.tec.hydra.script.EncodeResult;
import jmine.tec.hydra.script.EncodeScriptContext;
import jmine.tec.script.ScriptLogger;
import jmine.tec.script.impl.ScriptLoggerImpl;
import jmine.tec.script.persistent.context.impl.AbstractScriptExecutionContext;

/**
 * Contexto de execução de um script de encoding.
 * 
 * @author lundberg
 */
public class EncodeScriptContextImpl extends AbstractScriptExecutionContext<EncodeResult> implements EncodeScriptContext {

    private static final String SOURCE = "source";

    private static final String TEMPLATE_CONTEXT = "ctx";

    private static final String LOG = "log";
    
    /**
     * Construtor
     */
    public EncodeScriptContextImpl() {
        // OK
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void beforeExecution() {
        super.beforeExecution();
        this.getParameters().putParameter(TEMPLATE_CONTEXT, Collections.checkedMap(new HashMap<String, Object>(), String.class, Object.class), Map.class);
        this.getParameters().putParameter(LOG, new ScriptLoggerImpl(), ScriptLogger.class);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public EncodeResult getResult() {
        EncodeResult result = new EncodeResult();
        result.setTemplateContext((Map<String, Object>) this.getParameters().getParameterValues().get(TEMPLATE_CONTEXT));
        result.setScriptLogger((ScriptLogger) this.getParameters().getParameterValues().get(LOG));
        return result;
    }

    /**
     * {@inheritDoc}
     */
    public String getTracer() {
        return ((ScriptLogger) this.getParameters().getParameterValues().get(LOG)).getTraces();
    }

    /**
     * Define a origem da chamada
     * 
     * @param source source
     */
    private void setSource(Object source) {
        this.getParameters().putParameter(SOURCE, source, Object.class);
    }

    /**
     * {@inheritDoc}
     */
    public EncodeScriptContext prepare(Object source) {
        this.setSource(source);
        return this;
    }
}
